package com.xue.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xue.reggie.common.CustomException;
import com.xue.reggie.dto.SetmealDto;
import com.xue.reggie.entity.Setmeal;
import com.xue.reggie.entity.SetmealDish;
import com.xue.reggie.mapper.SetmealMapper;
import com.xue.reggie.service.SetmealDishService;
import com.xue.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService{

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private SetmealService setmealService;

    /**
     * 新增套餐，同时需要保存套餐和菜品之间的关联关系
     * @param setmealDto
     */
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {

        //保存套餐的基本信息setmeal表执行insert操作

        this.save(setmealDto);

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().map((item)->{
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());

        //保存套餐和菜品的关联信息setmealDish表执行insert操作

        setmealDishService.saveBatch(setmealDishes);



    }

    /**
     * 删除套餐，同时删除套餐和菜品的关联数据
     * @param ids
     */

    @Transactional
    @Override
    public void removeWithDish(List<Long> ids) {
        //查询套餐状态，是否可以删除
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId,ids);
        queryWrapper.eq(Setmeal::getStatus,1);

        int count = this.count(queryWrapper);
        if (count>0){  //不能删除，抛出异常（在售商品不可删除）
            throw new CustomException("套餐售卖中，不能删除");
        }
        //如果可以删除，先删除套餐表中数据   setmeal
        this.removeByIds(ids);


        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(SetmealDish::getSetmealId,ids);
        //删除关系表中的数据   setmealdish
        setmealDishService.remove(lambdaQueryWrapper);




    }

    /**
     * 套餐状态修改
     * @param status
     * @param ids
     */
    public void updateWithStatus(Integer status, List<Long> ids) {
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ids !=null,Setmeal::getId,ids);
        List<Setmeal> list = this.list(queryWrapper);
        for (Setmeal setmeal : list){
            if(setmeal != null){
                setmeal.setStatus(status);
                this.updateById(setmeal);
            }
        }
    }
}
